package com.example.h5shell.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraHelper {

    private Context context;
    private Activity activity;
    private Uri imageUri;

    public CameraHelper(Context context, Activity activity) {
        this.context = context;
        this.activity = activity;
    }

    public void takePhoto(int requestCode) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
            // 创建一个文件来保存图片
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // 错误处理
                ex.printStackTrace();
            }

            // 继续设置图片文件URI
            if (photoFile != null) {
                imageUri = FileProvider.getUriForFile(context,
                        "com.example.h5shell.fileprovider",
                        photoFile);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                // 检查是否需要添加权限（Android 6.0+）
                if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                }

                // 启动相机应用
                activity.startActivityForResult(takePictureIntent, requestCode);
            }
        }
    }

    private File createImageFile() throws IOException {
        // 创建一个唯一名称的图片文件
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir      /* 文件夹 */
        );

        // 保存文件路径，以便稍后访问
        return image;
    }

    // 获取图片URI（如果拍照成功）
    public Uri getImageUri() {
        return imageUri;
    }
}